const router = require('@koa/router')()
const { userLogin, userFind, userRegister } = require('../controllers/index')
const jwt = require('../utils/jwt')

router.prefix('/user')

router.post('/login', async (ctx) => {
    // 请求体中解析到的前端传递的参数，去数据库查询账号密码是否合法
    const { username, password } = ctx.request.body
    try {
        const result = await userLogin(username, password)
        // console.log(result);
        if (result.length) {
            // 找到数据
            const data = {
                id: result[0].id,
                nickname: result[0].nickname,
                username: result[0].username
            }
            // 签发 token
            let token = jwt.sign(data)
            ctx.body = {
                code: '800',
                data,
                msg: '登陆成功',
                token
            }
        } else {
            // 没找到
            ctx.body = {
                code: '804',
                msg: '登陆失败，请检查账号或密码',
                data: 'error'
            }
        }
    } catch (error) {
        ctx.body = {
            code: '805',
            data: error,
            msg: '服务器异常'
        }
    }

})

// 注册
router.post('/register', async (ctx) => {
    const { username, password, nickname } = ctx.request.body
    if (!username || !password || !nickname) {
        ctx.body = {
            code: '807',
            msg: '参数不完整'
        }
        return
    }

    try {
        // 判断账号是否存在
        const findRes = await userFind(username)
        if (findRes.length) {
            ctx.body = {
                code: '808',
                data: 'error',
                msg: '该账号已存在'
            }
            return
        }
        // console.log(findRes);
        // 写入账号
        const res = await userRegister({ username, password, nickname })
        // console.log(res);
        if (res.affectedRows) {
            ctx.body = {
                code: '800',
                data: 'success',
                msg: '注册成功'
            }
        } else {
            ctx.body = {
                code: '809',
                data: 'error',
                msg: '注册失败'
            }
        }
    } catch (error) {
        ctx.body = {
            code: '810',
            data: error,
            msg: '服务器异常'
        }
    }
})

module.exports = router